package com.lindroy.androidplayer.viewmodel

import androidx.lifecycle.MutableLiveData
import com.lindroy.androidplayer.base.viewmodel.BaseViewModel
import com.lindroy.androidplayer.extensions.request
import com.lindroy.androidplayer.extensions.yes
import com.lindroy.androidplayer.logic.model.WXArticleResp
import com.lindroy.androidplayer.logic.model.WXChapterResp
import com.lindroy.androidplayer.logic.network2.state.ResultState
import com.lindroy.androidplayer.logic.network2.apiService
import com.lindroy.androidplayer.logic.network2.statecallback.ListDataState

/**
 * @author Lin
 * @date 2021/4/8
 * @function
 */
class WXArticleViewModel : BaseViewModel() {
    /**
     * 页码，从0开始
     * 页码放在ViewModel中保存
     */
    private var pageNo = 1

    var chapterId = -1

    val wxChapters = MutableLiveData<ResultState<List<WXChapterResp>>>()

    /*val wxArticleLiveData = Transformations.switchMap(wxArticles) {
        Repository.getWXArticles(it.id, it.page)
    }*/

    val wxArticleLiveData: MutableLiveData<ListDataState<WXArticleResp>> = MutableLiveData()

    /**
     * 获取某一公众号下的文章
     */
    fun reqWXArticles(isRefresh: Boolean) {
        isRefresh.yes { pageNo = 1 }
        request({ apiService.getWxArticle(chapterId, pageNo) }, {
            wxArticleLiveData.value = ListDataState(
                success = true,
                isRefresh = isRefresh,
                isEmpty = it.isEmpty(),
                hasMore = it.hasMore(),
                isFirstEmpty = isRefresh && it.isEmpty(),
                listData = it.datas
            )
            pageNo++
        }, {
            wxArticleLiveData.value = ListDataState(
                success = false,
                isRefresh = isRefresh,
                errMessage = it.errorMsg,
                listData = arrayListOf()
            )
        })
    }

    //    fun getWXChapters() = Repository.getWXChapters()
    fun reqWXChapters() {
        request({ apiService.getWXChapter() }, wxChapters, isShowDialog = true)
    }


}